//------------------------------------------------------------------
//Got-Internet! Simple check if internet connection program. 
//Copyright (C) 2010  Manuel Villarejo
//------------------------------------------------------------------
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

#import "MVLoginItem.h"


@interface MVLoginItem ()
-(void) enable;
-(void) disable;
-(LSSharedFileListRef) loginItems;
-(CFURLRef) url;
-(LSSharedFileListItemRef) itemRef;
@end 

@implementation MVLoginItem

-(BOOL) enabled
{
	return [self itemRef] != nil;
}

-(void) setEnabled:(BOOL)enable
{
	if (enable) {
		[self enable];
	}
	else {
		[self disable];
	}
}

-(void) enable
{
	NSLog(@"Enable 'Start at Login'");
	LSSharedFileListInsertItemURL([self loginItems], kLSSharedFileListItemLast, NULL, NULL, [self url], NULL, NULL);
}

-(void) disable
{
	NSLog(@"Disable 'Start at Login'");
	LSSharedFileListItemRef itemRef = [self itemRef];
	if (itemRef != nil) {
		LSSharedFileListItemRemove([self loginItems], itemRef);
	}
}

-(LSSharedFileListRef) loginItems
{
	return LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
}

-(CFURLRef) url
{
	NSBundle *bundle = [NSBundle bundleForClass:[self class]];
	return (CFURLRef)[NSURL fileURLWithPath:[bundle bundlePath]];
}

-(LSSharedFileListItemRef) itemRef
{
	UInt32 seedValue;
	NSArray *loginItemsArray = (NSArray *)LSSharedFileListCopySnapshot([self loginItems], &seedValue);
	NSURL *bundleUrl = (NSURL *)[self url];
	LSSharedFileListItemRef result = nil;
	
	for (id item in loginItemsArray) {
		LSSharedFileListItemRef itemRef = (LSSharedFileListItemRef)item;
		CFURLRef url;
		
		if (LSSharedFileListItemResolve(itemRef, 0, (CFURLRef*) &url, NULL) == noErr) {
			if ([[(NSURL *)url path] isEqualToString: [bundleUrl path]]) {
				result = itemRef;
				break;
			}
		}
	}
	
	[loginItemsArray autorelease];
	return result;
}

@end
